package com.glela.platform.service.impl;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.glela.common.exception.BizException;
import com.glela.common.util.DateUtil;
import com.glela.constant.BizConstant;
import com.glela.platform.mapper.PromotionDetailMapper;
import com.glela.platform.mapper.PromotionGiftMapper;
import com.glela.platform.mapper.PromotionLogMapper;
import com.glela.platform.mapper.PromotionMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserPromotionMapper;
import com.glela.platform.model.Promotion;
import com.glela.platform.model.PromotionDetail;
import com.glela.platform.model.PromotionLog;
import com.glela.platform.model.User;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.service.UserPromotionService;
import com.glela.platform.vo.GoodsSimpleVo;
import com.glela.platform.vo.UserPromotionVo;

/**
 * @author liujie
 * @2016年10月25日
 */
@Service("userPromotionService")
public class UserPromotionServiceImpl implements UserPromotionService {

	private static Logger logger = LoggerFactory.getLogger(UserPromotionServiceImpl.class);

	@Autowired
	private UserPromotionMapper userPromotionMapper;
	@Autowired
	private PromotionGiftMapper promotionGiftMapper;
	@Autowired
	private PromotionDetailMapper promotionDetailMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private PromotionMapper promotionMapper;
	@Autowired
	private PromotionLogMapper promotionLogMapper;
	@Autowired
	private UserJournalMapper userJournalMapper;

	@Override
	public List<UserPromotion> selectUserPromotionByUserIdEx(long userId, long goodId, int brandId, long totalPrice) {
		return userPromotionMapper.selectUserPromotionByUserIdEx(userId, goodId, brandId, totalPrice);
	}

	@Override
	public List<UserPromotionVo> selectUserPromotionByUserIdEx(long userId, List<GoodsSimpleVo> list) {
		return userPromotionMapper.selectUserPromotionByUserIdEx2(userId, list);
	}

	@Override
	public UserPromotion selectUserPromotionByPromotionDetailIdAndUserId(int promotionDetailId, long userId) {
		return userPromotionMapper.selectUserPromotionByPromotionDetailIdAndUserId(promotionDetailId, userId);
	}

	@Override
	public int updateSubUserPromotionNumber(int promotionDetailId, long userId) {
		return userPromotionMapper.subUserPromotionNumber(promotionDetailId, userId);
	}

	/**
	 * 花38元购买会员后，赠送一个礼包给付费会员
	 * 
	 * @author 卫耀华
	 * @param userId
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void giveGiftPackageToVIP(long userId) throws BizException {
		logger.info("进入付费会员赠送礼包方法");
		User user = userMapper.selectByPrimaryKey(userId);
		if (user == null) {
			logger.warn("进入付费会员赠送礼包方法--无此用户--用戶ID=" + userId);
			throw new BizException("无此用户");
		}
		// 获取付费会员应该赠送的礼包的ID
		int promotionId = promotionGiftMapper.selectVIPPromotionId();
		if (promotionId == 0) {
			logger.warn("进入付费会员赠送礼包方法--赠送的礼包ID为空--礼包ID=" + promotionId);
			throw new BizException("赠送的礼包ID为空");
		}
		Promotion promotion = promotionMapper.selectByPrimaryKey(promotionId);
		if (promotion == null) {
			logger.warn("进入付费会员赠送礼包方法--无此礼包--礼包ID=" + promotionId);
			throw new BizException("无此礼包");
		}
		// 获取礼包里面的优惠券，分别绑定到用户
		List<PromotionDetail> promotionDetailList = promotionDetailMapper
				.selectPromotionDetailByPromotionId(promotionId);
		if (promotionDetailList != null && promotionDetailList.size() > 0) {
			logger.info("进入付费会员赠送礼包方法--该礼包下优惠券个数=" + promotionDetailList.size());
			for (PromotionDetail detail : promotionDetailList) {
				logger.info("进入付费会员赠送礼包方法--优惠券ID=" + detail.getId());
				// 判断优惠券的有效时间
				int detailbetweenDate = DateUtil.betweenTime(detail.getEffectiveTime(), detail.getExpirationTime());
				if (detailbetweenDate == 0) {
					continue;// 当前优惠券已过期 进行下一次判断
				}
				// 判断当前用户是否拥有
				UserPromotion userPromotion = userPromotionMapper
						.selectUserPromotionByPromotionDetailIdAndUserId(detail.getId(), user.getId());
				if (null == userPromotion) {
					// 校妆的优惠券的类型有：1.现金币 2.通用券 3.品牌券 4.预售券 5.商品券 6 达人激活码
					if (detail.getType() == 1) {
						int money = user.getMoney() + detail.getAmount();
						userMapper.updateUserInfonickMoneyById(user.getId(), money);
						// 添加流水账
						UserJournal userJournal = new UserJournal();
						userJournal.setType(BizConstant.TRANS_TYPE_PLUS);// +代表收入
						userJournal.setUserId(user.getId());
						userJournal.setMoney(detail.getAmount());
						userJournal.setPromotionDetailId(detail.getId());
						userJournal.setComment("付费会员获得妆币");
						userJournal.setStatus(BizConstant.USER_JOURNAL_STATUS_10);// 付费会员获得妆币
						userJournalMapper.insertUserJournal(userJournal);
						// 添加现金券类型优惠券 领取日志
						PromotionLog log = new PromotionLog();
						log.setPromotionDetailId(detail.getId());
						log.setUserId(userId);
						log.setDrawChannel(BizConstant.PROMOTION_CHANNEL_3);
						promotionLogMapper.insertPromotionLog(log);
					} else {// 2.通用券 3.品牌券 4.预售券 5.商品券,将这些券和用户做个绑定就好
						UserPromotion userPromotion2 = new UserPromotion();
						userPromotion2.setPromotionId(detail.getPromotionId());
						userPromotion2.setPromotionDetailId(detail.getId());
						userPromotion2.setType(detail.getType());
						userPromotion2.setUserId(user.getId());
						userPromotion2.setPromotionDetailName(detail.getPromotionDetailName());
						userPromotion2.setBrandId(detail.getBrandId());
						userPromotion2.setGoodId(detail.getGoodId());
						userPromotion2.setLimited(detail.getLimited());
						userPromotion2.setIsDiscount(detail.getIsDiscount());
						userPromotion2.setAmount(detail.getAmount());
						userPromotion2.setDiscount(detail.getDiscount());
						userPromotion2.setEffectiveTime(detail.getEffectiveTime());
						userPromotion2.setExpirationTime(detail.getExpirationTime());
						userPromotion2.setPromotionNumber(1);
						userPromotion2.setTargetSelfType(detail.getTargetSelfType());
						// 添加优惠券至用户持券表
						userPromotionMapper.insertUserPromotion(userPromotion2);
						logger.info("进入付费会员赠送礼包方法--添加优惠券至用户持券表成功，优惠券ID=" + detail.getId());
						// 添加优惠券领用日志
						PromotionLog log2 = new PromotionLog();
						log2.setPromotionDetailId(detail.getId());
						log2.setUserId(user.getId());
						log2.setDrawChannel(BizConstant.PROMOTION_CHANNEL_3);
						promotionLogMapper.insertPromotionLog(log2);
						logger.info("进入付费会员赠送礼包方法--添加优惠券至用户持券表成功，优惠券ID=" + detail.getId());
					}
				} else {
					// 优惠券是否只能使用一次，0是否，1是是，否的话，一个人可以拥有多张相同的优惠券，是的话，相同的优惠券每个人只能拥有一张
					if (detail.getIsOne() == 0) {
						logger.info("进入付费会员赠送礼包方法--优惠券可使用多次，次数要+1，优惠券ID=" + detail.getId());
						userPromotionMapper.updateUserPromotionNumber(userPromotion.getId());
						PromotionLog log3 = new PromotionLog();
						log3.setPromotionDetailId(detail.getId());
						log3.setUserId(user.getId());
						log3.setDrawChannel(BizConstant.PROMOTION_CHANNEL_3);
						promotionLogMapper.insertPromotionLog(log3);
					}
				}
			}
		}
	}

	@Override
	public boolean modifyToUse(int id) {
		if (id <= 0) {
			return false;
		}
		return userPromotionMapper.updateStatusToUse(id) == 1;
	}

	@Override
	public List<UserPromotionVo> selectUserPromotion(Long userId, Collection<Object> brandIds, Collection<Object> goodsIds) {
		if (userId==null) {
			return new LinkedList<>();
		}
		return userPromotionMapper.selectUserPromotion(userId,brandIds,goodsIds);
	}

}
